<template>
    <div class="action-main">
         <section class="order-main-header">
            <mt-header title="邀请返佣">
            <mt-button  icon="back" slot="left" @click="handleClose()"></mt-button>
            </mt-header>
        </section>
        <div class="load-content">
            <div class="load-main">
                <section class="desc">
                    <div class="onboarding">
                        <img src="../../assets/action/onboarding.png">
                    </div>
                </section>
                <section class="finance-card action-otc">
                    <dl >
                            <dt class="flex-between" style="">
                            <span @click="qroceVish()" class="user">我的专属邀请海报</span>
                            </dt>
                            <dd class="profit">
                                <div class="flex-between letter">
                                        <span>我的邀请链接</span>
                                        <span >https://biplus.vip....</span>
                                        <span class="copy"   @click="copys('https://biplus.vip/#/register?inviteCode='+sessionData.inviteCode)">复制</span>
                                </div>
                                <div class="flex-between letter">
                                    <span>我的邀请码</span>
                                    <span>{{sessionData.inviteCode}}</span>
                                    <span class="copy"  @click="copys(sessionData.inviteCode)">复制</span>
                                </div>
                            </dd>
                            <dd class="otc-ht">
                            </dd>
                    </dl>
                    <button><i class="mobile_icon_public"></i></button>
                </section>
                <section class="pro finance-card ">
                    <dl class="finance-cont">
                            <dt class="flex-between">
                            <h2>我的收益</h2>
                            <router-link to="action/record" class="rotate">  <img src="../../assets/my/right.png"></router-link>
                            </dt>
                            <dd class="profit">
                                <div class="group">
                                    <span><b>邀请人数</b><p>{{myProfitInfo.childrenNodeNum}}</p></span>
                                    <span><b>团队人数</b><p>{{myProfitInfo.teamNum}}</p></span>
                                    <span><b>团队业绩(USDT)</b><p>{{filter(myProfitInfo.teamTotal)}}</p></span>
                                </div>
                                <div class="group">
                                    <span><b>交易返佣(BZB)</b><p>{{filter(myProfitInfo.tradeCommission?myProfitInfo.tradeCommission:'0')}}</p></span>
                                    <span><b>分享奖励(BZB)</b><p>{{filter(myProfitInfo.ShareCommission?myProfitInfo.ShareCommission:'0')}}</p></span> 
                                    <span ><b>团队奖励(BZB)</b><p>{{filter(myProfitInfo.teamRewardCommission)}}</p></span>
                                </div>
                                <div class="group">
                                    <span><b>平级奖励(BZB)</b><p>{{filter(myProfitInfo.equalLevelCommission)}}</p></span>
                                        <span><b>全球分红(BZB)</b><p>{{filter(myProfitInfo.shareBonus?myProfitInfo.shareBonus:'0')}}</p></span>
                                </div>
                            </dd>
                            <dd class="otc-ht">
                            </dd>
                    </dl>
                </section>
                <section class="footer">
                    <div class="text">规则说明</div>
                    <div>
                        <p>1、好友接受邀请注册后，每产生一笔真实交易手续费，会产生20%的交易返佣。返佣会在当日统计，次日折合为BZB返佣至币币账户。</p>
                    <p>2、分享奖励</p>
                        <p> 
                        直接邀请1人注册并当日共识持币等值100USDT时，获得所有直接邀请用户共识收益的20%。（亏损不计算）
                        直推邀请2人注册并当日共识持币等值100USDT时，获得所有直接邀请用户共识收益的20%，二级邀请用户共识收益10%。（亏损不计算）
                        </p>
                        <p>3、社区节点代理收益</p>
                       
                         <p>（1）县级社区节点：直推6人，昨天总业绩2万，获得社区当日日利润15%的提成
                        奖励。 </p>
                         <p>（2）市级社区节点：直推6人，昨日总业绩7万，获得社区当日日利润20%的提成
                        奖励。（必须有两个县代，且不能是同一直推节点下） </p>
                         <p>（3）省级社区节点：直推6人，昨日总业绩20万，获得社区当日日利润25%的提成
                        奖励。（必须有两个市代，且不能是同一直推节点下）
                        </p>
                        <p>4、区域平级推荐奖励</p>
                        <p> 
                        A、区域代理商推荐同级代理商获得同级代理收益奖励的20%。
                        B、区域代理推荐区域代理的级别超过推荐人级别后将取消同级推荐奖励。
                        </p>
                        <p>5、区域贡献奖</p>
                                        <p>
                        当代理区域出现两个2个省级代理商（不能是同一直推节点下）可以获得平台全球分红5%（加权平分，日封顶1万USDT）
                        </p>
                    </div>
                </section>
            </div>
        </div>
        
        <div class="dialog" :style="{'left':shareWhiteLeft?'':'10000px'}">
            <div class="el-share"  >
                <div style="height:100%" class="flex-between">
                    <div ref="QrcodePage" class="card" id="view"  v-show="shareShow">
                            <div class="user">
                                    <img src="../../assets/my/share.png" alt="" class="qroce-share" >
                                    <div class="user-share">
                                        <div class="plus">
                                            <p class="plus">欢迎注册biplus</p>
                                            <p class="plus">{{sessionLoginName}}邀请你加入biplus</p>
                                            <p>长按识别二维码</p>
                                        </div>
                                        <div id="qrcode"></div>
                                    </div>
                            </div>
                        </div>
                    <div class="content_img" >
                        <div class="card_img" v-clickOut="clickOut">
                            <img :src="qrContentImage" id="thecanvas" style="width:100%;height:100%">
                        </div>
                    </div>
                </div>
                   <div class="share">
                        <div class="title">分享海报  <img @click="!hareWhiteLeft" class="error" src="../../assets/action/error.png"></div>
                        <div class="flex-between down">
                            <div class="flex-direction"><img src="../../assets/action/weixin.png" class="down-img" alt="" @click="downPayCircle(shareValue)"><p>微信好友</p></div>
                             <div class="flex-direction"><img src="../../assets/action/fir.png" class="down-img" alt="" @click="shareWeixin(shareValue)"> <p>朋友圈</p></div>
                            <div class="flex-direction"><img src="../../assets/action/down.png" class="down-img" alt="" @click="updatedDown(qrContentImage)"> <p>保存到本地相册</p></div>
                        </div>
                   </div>
                <!-- <vue-native-share :shareMenu="shareMenu" :config="config" /> -->
            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios'
import { Toast,Indicator } from 'mint-ui';
import vueNativeShare from 'vue-native-share'
import html2canvas from 'html2canvas';

export default {
    components:{
       vueNativeShare
    },
    name:'my',
   data(){
         return {
             shareWhiteLeft:false,
             shareShow:true,
             qrContentImage:'',
             spreadDetail:'',
             sessionData:'',myProfitList:'',
             myProfitInfo:'',
             rewards:'',
             spreadDetailTotal:'',
             inviteCoinName:'',
          shareMenu: [0,1,5,],
          sessionLoginName:'',
          shareValue:'',
    config: {
    title: '分享标题',
    desc:'描述',
    img:'图片地址',
    img_title:'图片标题',
    link: '当前链接',
    success: () => {console.log('success')}, //成功回调
    cancel: () => {console.log('cancel')}, //取消回调
    }
         }
    },
    mounted() {
        var _this=this;
         this.$http.post('v1/session?'+ new Date().getTime(),).then((res)=>{
            this.sessionData=res.data.data;
              this.getOtcList();
                this.qrcode();
              this.sessionLoginName=res.data.data.loginName.substring(0,3)+'**'+res.data.data.loginName.substring(res.data.data.loginName.length-3,res.data.data.loginName.length);
       })
    this.spreadAil();
      this.createImg();
    plus.share.getServices(function(s){
          _this.shareValue=s;
    },function(e){
    });
    },
    methods: {
        downPayCircle(share){
             var target='';
  for(var i in share) {
    if('weixin'==share[i].id){
        target=share[i];
    }
  }
    　　　let msg = {
　　　　type: 'web',　　//分享的内容的类型 
　　　　title:  this.sessionLoginName+'邀请您加入biplus',
　　　　content: '请前往biplus注册',
　　　　thumbs: ['https://biplus.vip/static/img/login-logo.98655a2.png'],
　　　　href: "https://biplus.vip/#/register?inviteCode="+this.sessionData.inviteCode,
　　　　extra:{scene:"WXSceneSession"} // 'WXSceneSession'分享给好友，'WXSceneTimeline'分享到朋友圈
　　}
    target.send( msg, function(e){
        // if(e){
        //     Toast(e);
        // }
        }, function(e){
            alert(e)
            if(e.code=='-8'){
                 Toast("失败：未安装微信客户端");
            }
           
        });
    },
 shareWeixin(share){
            var target='';
        for(var i in share) {
            if('weixin'==share[i].id){
                target=share[i];
            }
        }
    　let msg = {
        　　　　title:"Biplus共识交易平台",
    // 　　　　pictures:[this.qrContentImage],
      content:"Biplus共识交易平台",
        href:"https://biplus.vip/#/register?inviteCode="+this.sessionData.inviteCode,
    　　　　extra:{scene:"WXSceneTimeline"}
    　　}
    target.send( msg, function(e){
        // if(e){
        //     alert(e);
        // }
        }, function(e){
            if(e.code=='-8'){
                 Toast("失败：未安装微信客户端");
            }
        });
     },
     updatedDown(url) {
           Indicator.open({
        text: '下载中...',
        spinnerType: 'fading-circle'
        });
                var imgFile = this.dataURLtoFile(url); 
            let formData = new FormData()
                        formData.append('img',imgFile,imgFile.name)
                        formData.append('type',1);
                        this.$http.upload('/v1/account/upload.html',formData,{
                            headers: { 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7j36XuEUfKHvtxmd' }
                        }).then(res=>{
                       res = res.data
                            if(res.code == 200){
                        this.createDownload(res.data);
                        }
                        }).catch(err=>{
            })
     },
     createDownload(url) {
    /*设置下载路径*/
     let loadUrl = 'https://biplush.oss-ap-southeast-1.aliyuncs.com/'+url;
    //设置保存路径
    var relativePath =  "_downloads/" + '/upload/others/'+(new Date()).getTime()+'_BxNIU.png';
    //alert(relativePath);
    plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
        // Toast("文件已存在," );
        delFile(relativePath)
    }, function(e) {
      //  alert("文件不存在,联网下载=" + relativePath);
        setImgFromNet(loadUrl, relativePath);
    });
 /*给图片标签<img>设置本地图片
         * imgId 图片标签<img>的id
         * relativePath 本地相对路径 例如:"_downloads/logo.jpg"
         */
        function setImgFromLocal(imgId, relativePath) {
                //本地相对路径("_downloads/logo.jpg")转成SD卡绝对路径("/storage/emulated/0/Android/data/io.dcloud.HBuilder/.HBuilder/downloads/logo.jpg");
                var sd_path = plus.io.convertLocalFileSystemURL(relativePath);
            }
    function setImgFromNet(loadUrl, relativePath) {
        //创建下载任务
        var dtask = plus.downloader.createDownload(loadUrl, {filename:relativePath}, function(d, status) {
            if(status == 200) {
                //下载成功
                 plus.storage.setItem("relativePath", relativePath); //存储db文件路径名
                  setImgFromLocal('', d.filename);
                plus.gallery.save(relativePath,function() {//保存到相册方法
                Indicator.close();
            Toast('已保存,请到到手机相册查看');
            }, function() {
            Toast('保存失败，请重试！');
            });
            } else {
                //下载失败,需删除本地临时文件,否则下次进来时会检查到文件已存在
              //  Toast("下载失败=" + status + "==" + relativePath);
                if(relativePath != null)
                    delFile(relativePath);
            }
        });
        //启动下载任务
        dtask.start();
    }
    /*删除指定文件*/
    function delFile(relativePath) {
        plus.io.resolveLocalFileSystemURL(relativePath, function(entry) {
            entry.remove(function(entry) {
                setImgFromNet(loadUrl, relativePath);
            }, function(e) {
            });
        });
    }
},
  dataURLtoFile(dataurl, filename = 'file') {
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let suffix = mime.split('/')[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            })
            },
             downPay(){
            //必须同源才能下载
                // var alink = document.createElement("a");
                // alink.href = this.qrContentImage;
                // alink.download = "pic"; //图片名
                // alink.click();
             //   plus.runtime.openURL("http://192.168.0.106:8003/#/action");//成功跳转了
            },
        qroceVish(){
                 this.shareWhiteLeft=true;
        },
          qrcode () {
       //     console.log("https://biplus.vip/#/register?inviteCode="+this.sessionData.inviteCode)
           var qrcode = new QRCode(document.getElementById("qrcode"), {
                width: 100,
                height: 100,
            });
               qrcode.clear(); // clear the code.
           qrcode.makeCode("https://biplus.vip/#/register?inviteCode="+this.sessionData.inviteCode); // make another code.
        },
        createImg() {
    var that = this;
       let shareContent = document.getElementById('view'), //需要截图的包裹的（原生的）DOM 对象
           width = shareContent.clientWidth, //shareContent.offsetWidth; //获取dom 宽度
           height = shareContent.clientHeight, //shareContent.offsetHeight; //获取dom 高度
           canvas = document.createElement("canvas"), //创建一个canvas节点
           scale = 1; //定义任意放大倍数 支持小数
       canvas.width = "420"; //定义canvas 宽度 * 缩放
       canvas.height = "800"; //定义canvas高度 *缩放
    //    canvas.style.width = (shareContent.clientWidth * scale) / 100 + "rem";
    //    canvas.style.height = (shareContent.clientHeight * scale) / 100 + "rem";
      
       canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
       let opts = {
           scale: scale, // 添加的scale 参数
           canvas: canvas, //自定义 canvas
           logging: false, //日志开关，便于查看html2canvas的内部执行流程
           width: "120", //dom 原始宽度
           height: "200",
           useCORS: true
       };
         setTimeout(() => {
              window.pageYOffset = 0;
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0;
    html2canvas(shareContent, opts).then(function(canvas) {
           that.qrContentImage= canvas.toDataURL("image/png", 1.0);
                   that.qroceShow=false;
           that.shareShow=false;
       }).catch(function (reason) {
       });
      }, 500);
           
    },
    copys(data){
             if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS
              var input = document.createElement("input");
              input.setAttribute('readonly', 'readonly');
             var message=data;
            input.value = message;
            document.body.appendChild(input);
            input.select();
            input.setSelectionRange(0, input.value.length), document.execCommand('Copy');
            input.style.display='none';
              input.className = 'oInput';
            document.body.removeChild(input);
             input.focus(); 
                 Toast("复制成功");
            }else{
        var Url2=data;
          var oInput = document.createElement('input');
          oInput.setAttribute('readonly', 'readonly');
        oInput.value = Url2;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.className = 'oInput';
        oInput.style.display='none';
        Toast("复制成功");
        }
    },
          copy(data) {  
        var Url2=data;
         var oInput = document.createElement('input');
        oInput.value = Url2;
          oInput.style.display='none';
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.className = 'oInput';
        Toast("复制成功");
           // }
        },
         spreadAil(){
           this.$http.post('/v1/account/spreadDetail').then((res)=>{
                if(res.data.code==200){
                    this.spreadDetail=res.data.data;
                    this.spreadDetailTotal=res.data.data.total;
                }
             })
     },
         myProfit(current){
                  this.$http.post('/v2/bankerWallet/myProfit',{userId: this.sessionData.id,fViFId:current.coinId}).then((res)=>{
              if(res.data.code==0){
                    this.myProfitInfo=res.data.data;
                }
             })
        },
         filter(x){
            if(isNaN(x)){
                return '0'
            }
            var pos=4;
            var f = Math.round(x * Math.pow(10, pos)) / Math.pow(10, pos);
            var s = f.toString();
            var rs = s.indexOf('.');
            if (rs < 0) {
                rs = s.length;
                s += '.';
            }
            while (s.length <= rs +  pos) {
                s += '0';
            }
            return f.toFixed(pos);
        }, 
       clickOut(el){
            this.shareWhiteLeft=false;
          },
        getOtcList(){this.$http.post('/v2/market/allcoins',).then((res)=>{
                let tickers = res.data;
                 let coinGroup = {}
                    let param = location.hash.match(new RegExp(".*" + 'symbol' + "=([^\&]*)(\&?)", "i"));
                    let symbol = param && !isNaN(param[1]) ? param[1] : 0;
                    let current = null;
                    for (let i = 0; i < tickers.length; i++) {
                        let ticker = tickers[i]
                        if(ticker.report){
                            current = ticker
                        }
                    }
                     this.myProfit(current);
             })
          },
        handleClose(){
                this.$router.go(-1);
            },
    },
     directives : {
                clickOut: {
                    bind: function(el, binding) {
                        let  self=this;
                    function handler(e) {
                            if(e.target.className=="user"){
                                return false
                            }
                        if (el.contains(e.target)){
                            return false
                    }
                    
                    if (binding.expression) {
                        binding.value()
                    }
                    }
                    el.handler = handler
                    document.addEventListener('click', el.handler)
                    },
                    unbind: function(el) {
                    document.removeEventListener('click', el.handler)
                    }    
                }
                },
}
</script>
<style lang="less" scoped>
.load .action-main .pro dl dt{
    height: 100px;
    line-height: 100px
}
    .action-main{
        .group b {
    line-height: 60px;
    color: rgba(173, 173, 216, 1);
    font-size:24px;
    }
        .footer{
            .text{
                text-align: center;
                font-size: 28px;
                margin-top: 10px;
                margin-bottom: 18px;
                color: rgba(224, 224, 249, 1)
            }
            font-size:24px;
            color: rgba(173, 173, 216, 1);
            padding: 30px;
            line-height:44px;
        }
        .onboarding{
            display: flex;
            justify-content: center;
        }
        .action-otc{
                margin-left:  30px; 
                 margin-right:  30px; 
             height: 284px;
        }
        .pro{
             margin-left:  30px; 
            margin-right:  30px; 
            margin-top: 40px;
             height: 504px;
        }
    }
    .mint-header {
    height:100px;
    font-size: 32px;
    background-color: #161736 ;
    color: #E0E0F9;
}
.rotate img{
    transform:rotate(-180deg);
-webkit-transform:rotate(-180deg);
-moz-transform:rotate(-180deg);
-o-transform:rotate(-180deg);
-mz-transform:rotate(-180deg);
}
.user .user-share .plus{
    font-size: 18px;
}
.group p{
    line-height: 60px;
}
.action-main {
    .finance-card dl {
    color: rgba(224, 224, 249, 1);
    padding: 32px 40px 32px 40px;
}
.flex-direction{
    display: flex;
    flex-direction: column;
    color: rgba(224, 224, 249, 1);
    align-items: center;
    font-size:20px;
    width: 33%;
    img{
        width: 52px;
        margin-bottom: 20px;
    }
}
.finance-card dl dt {
    font-size: 32px;
    line-height: 64px;
    margin-bottom: 20px;
    height: 64px;
    span{
       background:rgba(134,134,192,1);
border-radius:4px;
padding:  0px 25px 0px 25px;
font-size:28px;
color: #161736;
    }
}
.share{
    width: 90%;
    margin: 60px auto 0px auto;
    background:rgba(34,34,64,0.7);
    height:202px;
    border-radius:4px;
    .title{
        height: 80px;
        line-height: 80px;
        text-align: center;
        color: rgba(224, 224, 249, 1);
    }
    .down{
        padding-left: 30px;
        padding-right: 30px;
    }
    .error{
        width: 18px;
        float: right;
        position: relative;
        top:20px;
        right: 20px;
    }
}
.finance-card dl dd {
    font-weight: 400;
}
   .finance-card {
       .copy{
           color: rgba(82, 152, 254, 1);
       }
    background:rgba(34,34,64,1);
    border-radius:14px;
    position: relative;
    .letter{
        span:nth-child(2){
            width: 60%;
        }
         span:nth-child(1){
            width: 30%;
        }
        height: 80px;
        span{
            line-height: 80px;
        }
    }
    .profit .group{
         height:110px;
         flex-direction: row;
        display: flex;
        span{
            width: 33%;
            text-align: center
        }
    }
   }
   }
    .flex-between{
      display: flex;
        justify-content: space-between;
    }
       .card_img{
        width:428px;height:760px;
        }
        .qroce-share{
            width:420px;height:640px
        }
        .user{
            p{
                height: 40px;
                line-height: 40px;
                margin-top: 10px;
                margin-left: 30px;
                font-size: 18px;
                color: #161736;
                margin-right: 40px;
            }
        }
        .content_img{
            height: 100%;
            width: 100%;
            display: flex;
            align-items:center;
            justify-content: center;
        }
        #qrcode{
            width: 100px;
            height: 100px;
            margin-top: 30px;
            position: relative;
            left: 20px;
        }
        .user-share{
            display: flex;
            flex-direction: row;
            background: #fff;
        }
        .user{
            height: 100%;
        }
        .el-share{
        padding: 20px;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    position: relative;
    height: 55%;
        }
        .el-share-white{
            .user{
            p{
            font-size: 32px;
            }   
            }
            .user-share{
                height: 100%;
                display: flex;
        justify-content: space-between;
        background: #fff;
            }
            height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    position: relative;
        }
        .dialog,.dialog-white{
            position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.65);
    z-index: 9999;
        }
       #nativeShare{
           margin-bottom: -50px;
           margin-top: 60px;
       }
        .load-content{
           position: absolute;
           top:100px;
           bottom: 30px;
           overflow-y: scroll;
           -webkit-overflow-scrolling:touch
       }
       .load-main{
           height: 2000px;
       }
</style>